/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package Ui;

import Model.DB;
import java.awt.event.KeyEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;

/**
 *
 * @author William
 */
public class VentanaPrincipal extends javax.swing.JFrame {

    DB db = new DB();
    private VentanaPrincipalEstandar2 ventanaPrincipalEstandar;
    //prueba
    public VentanaPrincipal() {
        initComponents();
        //panelPrincipalEstandar = new PanelAccesoEstandar();
        //cards = new CardLayout();
        //this.getContentPane().setLayout(cards);
        //mainCards = new JPanel();
        //mainCards.setLayout(cards);
        //add(panelImagenInicio);
        //add(panelPrincipalEstandar);
        
        //add(mainCards);
        //this.add(panelPrincipalEstandar);
        //loginUI.removeAll();
        //loginUI.setLayout(new GridLayout(0,3));
        //loginUI.add(new JLabel(""));
        //loginUI.add(LoginPanel);
        
    }
    
    private void ingresarModoEstandar(){
                
        VentanaPrincipalUsuarioEstandar ventanaEstandar = new VentanaPrincipalUsuarioEstandar();
        //ventanaEstandar.setUserActual(campoUsuario.getText());
        this.setVisible(false);
        this.dispose();
    }
    
    private int existeUser(){
        
      //  return db.check(campoUsuario.getText() ,campoPasswd.getText());
        Connection conexion=null;
        Statement sentencia=null;
        ResultSet resultado=null;
        
        try {
            Class.forName("org.postgresql.Driver");
        }catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try{
            conexion = DriverManager.getConnection(cadenaConexion);
            sentencia = conexion.createStatement();
            String consultaSQL = "select id,contrasena,rol from usuario where id='"+campoUsuario.getText()+"' and contrasena='"+campoPasswd.getText()+"'";
            resultado = sentencia.executeQuery(consultaSQL);
            int rol=0;
            
            while (resultado.next()) {
                if(resultado.getString(rol).equals("'a'")){
                    return 1;
                }
                else{
                    return 2;
                }
            }
            
            return -1;
            
            
            
            
            
        }catch (SQLException e) {   
            JOptionPane.showMessageDialog(null, "\nProblema en la base de datos \nImposible consultar usuarios correctamente", "Error", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
            conexion = null;
            
        }
        finally {
            if (resultado != null) {
                try {
                resultado.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (sentencia != null) {
                try {
                sentencia.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (conexion != null) {
                try {
                conexion.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return 0;
    }
    

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        panelImagenInicio = new org.edisoncor.gui.panel.PanelImage();
        mainUI = new javax.swing.JPanel();
        LoginPanel = new javax.swing.JPanel();
        etqPasswd = new org.edisoncor.gui.label.LabelRound();
        btnAceptar = new org.edisoncor.gui.button.ButtonRect();
        logoAcademia = new javax.swing.JLabel();
        campoPasswd = new javax.swing.JPasswordField();
        etqUsuario = new org.edisoncor.gui.label.LabelRound();
        campoUsuario = new javax.swing.JTextField();
        llaves = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Academia De Música Moderna");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        panelImagenInicio.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Img/FondoInicioSesion2.jpg"))); // NOI18N

        mainUI.setOpaque(false);

        LoginPanel.setOpaque(false);

        etqPasswd.setBackground(new java.awt.Color(0, 102, 204));
        etqPasswd.setText("Contraseña:");

        btnAceptar.setBackground(new java.awt.Color(0, 102, 204));
        btnAceptar.setText("Aceptar ");
        btnAceptar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                Ingresar(evt);
            }
        });
        btnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAceptarActionPerformed(evt);
            }
        });

        logoAcademia.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Img/logotipo5.png"))); // NOI18N

        etqUsuario.setBackground(new java.awt.Color(0, 102, 204));
        etqUsuario.setText("Usuario:");

        campoUsuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                campoUsuarioActionPerformed(evt);
            }
        });
        campoUsuario.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                campoUsuarioKeyTyped(evt);
            }
        });

        llaves.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Img/alert_icon_login.png"))); // NOI18N

        javax.swing.GroupLayout LoginPanelLayout = new javax.swing.GroupLayout(LoginPanel);
        LoginPanel.setLayout(LoginPanelLayout);
        LoginPanelLayout.setHorizontalGroup(
            LoginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(LoginPanelLayout.createSequentialGroup()
                .addGap(175, 175, 175)
                .addGroup(LoginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(etqPasswd, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(etqUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(campoUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(LoginPanelLayout.createSequentialGroup()
                .addGap(317, 317, 317)
                .addComponent(campoPasswd, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, LoginPanelLayout.createSequentialGroup()
                .addContainerGap(54, Short.MAX_VALUE)
                .addGroup(LoginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, LoginPanelLayout.createSequentialGroup()
                        .addComponent(logoAcademia)
                        .addGap(41, 41, 41))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, LoginPanelLayout.createSequentialGroup()
                        .addComponent(btnAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(llaves)
                        .addGap(219, 219, 219))))
        );
        LoginPanelLayout.setVerticalGroup(
            LoginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(LoginPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(logoAcademia)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 46, Short.MAX_VALUE)
                .addGroup(LoginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(etqUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(campoUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(LoginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(etqPasswd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(campoPasswd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(LoginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(llaves)
                    .addComponent(btnAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(87, 87, 87))
        );

        javax.swing.GroupLayout mainUILayout = new javax.swing.GroupLayout(mainUI);
        mainUI.setLayout(mainUILayout);
        mainUILayout.setHorizontalGroup(
            mainUILayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainUILayout.createSequentialGroup()
                .addGap(37, 37, 37)
                .addComponent(LoginPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(37, Short.MAX_VALUE))
        );
        mainUILayout.setVerticalGroup(
            mainUILayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainUILayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(LoginPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(22, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout panelImagenInicioLayout = new javax.swing.GroupLayout(panelImagenInicio);
        panelImagenInicio.setLayout(panelImagenInicioLayout);
        panelImagenInicioLayout.setHorizontalGroup(
            panelImagenInicioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelImagenInicioLayout.createSequentialGroup()
                .addGap(132, 132, 132)
                .addComponent(mainUI, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(139, Short.MAX_VALUE))
        );
        panelImagenInicioLayout.setVerticalGroup(
            panelImagenInicioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelImagenInicioLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(mainUI, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(213, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panelImagenInicio, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panelImagenInicio, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        setSize(new java.awt.Dimension(976, 678));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void campoUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_campoUsuarioActionPerformed
        // TODO add your handling code here:
          
    }//GEN-LAST:event_campoUsuarioActionPerformed

    private void Ingresar(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_Ingresar
        // TODO add your handling code here:
        if(campoUsuario.getText().isEmpty() && campoPasswd.getText().isEmpty()){
            JOptionPane.showMessageDialog(null, "Ha olvidado ingresar su nombre de usuario y contraseña. \nPor favor ingresar los datos para iniciar sesión.", "Advertencia", JOptionPane.WARNING_MESSAGE);
        }
        else{
            if(campoUsuario.getText().isEmpty()){
                JOptionPane.showMessageDialog(null, "Ha olvidado ingresar su nombre. \nPor favor ingrese su nombre de usuario para iniciar sesión.", "Advertencia", JOptionPane.WARNING_MESSAGE);
            }
            else{
                if(campoPasswd.getText().isEmpty()){
                    JOptionPane.showMessageDialog(null, "Ha olvidado ingresar su contraseña. \nPor favor ingrese su contraseña de usuario para iniciar sesión.", "Advertencia", JOptionPane.WARNING_MESSAGE);
                }
                else{
                    if(existeUser()==2){
                        ingresarModoEstandar(); 
                    }
                    if(existeUser()==1){
                        VentanaModuloAdministrador admin = new VentanaModuloAdministrador();
                        admin.setUserActual(campoUsuario.getText());
                        admin.setVisible(true);
                    }
                   if(existeUser()==0){
                        JOptionPane.showMessageDialog(null, "\nUsuario y contraseña incorrectos \nPor favor ingresar datos correctamente", "Error", JOptionPane.ERROR_MESSAGE); 
                    }
                   
                }
            }
        }
    }//GEN-LAST:event_Ingresar

    private void campoUsuarioKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_campoUsuarioKeyTyped
        // TODO add your handling code here:
        char c = evt.getKeyChar();
        if(!((Character.isAlphabetic(c)) || (Character.isDigit(c))||(c == KeyEvent.VK_BACK_SPACE)||(c== KeyEvent.VK_DELETE))){
            getToolkit().beep();
            evt.consume();
        }
    }//GEN-LAST:event_campoUsuarioKeyTyped

    private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAceptarActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_btnAceptarActionPerformed

    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VentanaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VentanaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VentanaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VentanaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new VentanaPrincipal().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel LoginPanel;
    private org.edisoncor.gui.button.ButtonRect btnAceptar;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JPasswordField campoPasswd;
    private javax.swing.JTextField campoUsuario;
    private org.edisoncor.gui.label.LabelRound etqPasswd;
    private org.edisoncor.gui.label.LabelRound etqUsuario;
    private javax.swing.JLabel llaves;
    private javax.swing.JLabel logoAcademia;
    private javax.swing.JPanel mainUI;
    private org.edisoncor.gui.panel.PanelImage panelImagenInicio;
    // End of variables declaration//GEN-END:variables
    private static final String cadenaConexion = "jdbc:postgresql://localhost/SMAAMDB?" + "user=postgres&password=root";
    
}
